package org.barman.servlet;

import java.io.IOException;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.barman.dao.OrderDAO;
import org.barman.exception.CustomMessageException;
import org.barman.exception.ValidationException;
import org.barman.pojo.Order;
import org.barman.pojo.OrderItem;
import org.barman.pojo.User;
import org.barman.pojo.UserRole;

@WebServlet("/ManageOrderServlet")
public class ManageOrderServlet extends ExceptionHandlingHttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doExceptionHandledPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException, CustomMessageException {

		User loggedUser = (User) request.getSession().getAttribute("loggedUser");

		if (loggedUser == null) {
			throw new ValidationException("You are not logged in");
		}

		if (UserRole.WAITER != loggedUser.getRole()) {
			throw new ValidationException("You should be a waiter to make orders");
		}

		String[] itemIds = request.getParameterValues("itemIds[]");
		String[] itemQuantities = request.getParameterValues("itemQuantities[]");

		List<OrderItem> orderItems = new ArrayList<OrderItem>();
		for (int i = 0; i < itemIds.length; i++) {
			OrderItem orderItem = new OrderItem();
			orderItem.setItemId(Integer.parseInt(itemIds[i]));
			orderItem.setQuantity(Integer.parseInt(itemQuantities[i]));
			orderItems.add(orderItem);
		}

		Order order = new Order();
		order.setStatus("created");
		order.setOrderItems(orderItems);
		order.setWaiter(loggedUser);
		order.setCreated(new Date(System.currentTimeMillis()));

		OrderDAO orderDAO = new OrderDAO();
		orderDAO.insert(order);

		response.sendRedirect("waiter/main.jsp");

	}
}
